package de.tsajar.es.physics.interpolation;

import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.simsilica.es.Entity;
import com.simsilica.es.EntitySet;
import de.tsajar.es.EntitySystemAppState;
import de.tsajar.es.position.PositionComponent;

/**
 *
 * @author Eike Foede
 */
public class LinearInterpolationSystem extends EntitySystemAppState{

    private EntitySet es;
    private float tpUpdate;
    private float tCount;

    @Override
    public void initialize(AppStateManager stateManager, Application app) {
        super.initialize(stateManager, app);
        es = ed.getEntities(LinearInterpolationComponent.class, PositionComponent.class);
        
    }
    
    public LinearInterpolationSystem(float tpUpdate) {
        this.tpUpdate = tpUpdate;
    }

    @Override
    public void update(float tpf) {
        tCount += tpf;
        if (tCount > tpUpdate) {
            tCount %= tpUpdate;
            es.applyChanges();
            for (Entity e : es) {
                Vector3f oldPos = e.get(LinearInterpolationComponent.class).getNewPosition();
                Vector3f newPos = e.get(PositionComponent.class).getPosition();
                e.set(new LinearInterpolationComponent(oldPos, newPos));
            }
        }
        for (Entity e : es) {
            LinearInterpolationComponent lic = e.get(LinearInterpolationComponent.class);
            ed.setComponent(e.getId(), new InterpolatedPositionComponent(
                    FastMath.interpolateLinear(tCount / tpUpdate,
                    lic.getOldPosition(),
                    lic.getNewPosition())));
        }
    }
}
